package com.stylefeng.guns.rest.modular.wz.api.v1;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.support.HttpKit;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.config.properties.JwtProperties;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnWzAdv;
import com.stylefeng.guns.rest.enums.EnWzCoupon;
import com.stylefeng.guns.rest.enums.EnWzPrize;
import com.stylefeng.guns.rest.enums.EnWzUser;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.util.AliPushUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商户模块
 * @author ruiyifeng
 * @since 2018-04-26
 */
@RestController
@RequestMapping("/wz/api/v1/wzMerchant/")
public class WzMerchantApi extends ApiBaseController{

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzUserAdvRecordMapper userAdvRecordMapper;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private WzUserInfoMapper userInfoMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private WzPrizeMapper prizeMapper;
    @Autowired
    private WzPrizeWinnersMapper prizeWinnersMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzUserFinanceRecordMapper userFinanceRecordMapper;
    @Autowired
    private WzAdvShareMapper advShareMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private WzAdvMapMapper advMapMapper;


    /**
     * 地址列表
     */
    @RequestMapping("userInfoList")
    public Res userInfoList(@RequestBody ParamMap paramMap){
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
            List<WzUserInfo> userInfos = userInfoMapper.selectList(new EntityWrapper<WzUserInfo>().eq("type", EnWzUser.USERINFO_TYPE_MERCHANT.getIndex()).eq("user_code",userCode));
            paramMap.put("list",userInfos);
        return Res.success(paramMap);
    }

    /**
     * 地址新增修改
     */
    @Transactional
    @PostMapping("userInfoUpdate")
    public Res userInfoUpdates(@RequestBody ParamMap paramMap){
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        int isDefault = paramMap.getIntMisValid("isDefault");
        String userInfoId = paramMap.getStrValid("userInfoId");
        WzUserInfo userInfo = new WzUserInfo();
        if(!StringUtils.isBlankStr(userInfoId)){
            userInfo = userInfoMapper.selectById(userInfoId);
        }
        String merchantTel = paramMap.getStrMisValid("merchantTel");
        String merchantAddress = paramMap.getStrValid("merchantAddress");
        String merchantName = paramMap.getStrMisValid("merchantName");
        String merchantLongitude = paramMap.getStrMisValid("merchantLongitude");
        String merchantLatitude = paramMap.getStrMisValid("merchantLatitude");
        String merchantArea = paramMap.getStrMisValid("merchantArea");
        String merchantFullAddress = paramMap.getStrMisValid("merchantFullAddress");
        String adCode = paramMap.getStrValid("adCode");
        //修改默认
        if(isDefault == EnWzUser.USERINFO_isDefault_true.getIndex()){
            List<WzUserInfo> userInfos = userInfoMapper.selectList(new EntityWrapper<WzUserInfo>().eq("user_code",userCode).eq("type",EnWzUser.USERINFO_TYPE_MERCHANT.getIndex()).eq("is_default",EnWzUser.USERINFO_isDefault_true.getIndex()));
            for(WzUserInfo u:userInfos){
                u.setIsDefault(EnWzUser.USERINFO_isDefault_false.getIndex());
                userInfoMapper.updateById(u);
            }
        }
        userInfo.setMerchantFulladdress(merchantFullAddress);
        userInfo.setMerchantArea(merchantArea);
        if(!StringUtils.isBlankStr(merchantAddress)){
            userInfo.setMerchantAddress(merchantAddress);
        }
        userInfo.setAdCode(adCode);
        userInfo.setMerchantTel(merchantTel);
        userInfo.setMerchantName(merchantName);
        userInfo.setMerchantLatitude(merchantLatitude);
        userInfo.setMerchantLongitude(merchantLongitude);
        userInfo.setUserCode(userCode);
        userInfo.setIsDefault(isDefault);
        userInfo.setType(EnWzUser.USERINFO_TYPE_MERCHANT.getIndex());
        if(StringUtils.isBlankStr(userInfoId)){
            userInfoMapper.insert(userInfo);
        }else{
            userInfoMapper.updateById(userInfo);
            List<WzAdvMap> advMaps = advMapMapper.selectList(new EntityWrapper<WzAdvMap>().eq("user_info_id",userInfoId));
            for(WzAdvMap advMap : advMaps){
                advMap.setLongitude(userInfo.getMerchantLongitude());
                advMap.setLatitude(userInfo.getMerchantLatitude());
                advMap.setMerchantFullAddress(userInfo.getMerchantFulladdress());
                advMap.setMerchantTel(userInfo.getMerchantTel());
                advMapMapper.updateById(advMap);
            }
        }
        return Res.success();
    }

    /**
     * 地址新增修改
     */
    @Transactional
    @PostMapping("userInfo.update")
    public Res userInfoUpdate(@RequestBody ParamMap paramMap){
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        int isDefault = paramMap.getIntMisValid("isDefault");
        String userInfoId = paramMap.getStrValid("userInfoId");
        WzUserInfo userInfo = new WzUserInfo();
        if(!StringUtils.isBlankStr(userInfoId)){
            userInfo = userInfoMapper.selectById(userInfoId);
        }
        String merchantTel = paramMap.getStrMisValid("merchantTel");
        String merchantAddress = paramMap.getStrValid("merchantAddress");
        String merchantName = paramMap.getStrMisValid("merchantName");
        String merchantLongitude = paramMap.getStrMisValid("merchantLongitude");
        String merchantLatitude = paramMap.getStrMisValid("merchantLatitude");
        String merchantArea = paramMap.getStrMisValid("merchantArea");
        String merchantFullAddress = paramMap.getStrMisValid("merchantFullAddress");
        String adCode = paramMap.getStrValid("adCode");
        //修改默认
        if(isDefault == EnWzUser.USERINFO_isDefault_true.getIndex()){
            List<WzUserInfo> userInfos = userInfoMapper.selectList(new EntityWrapper<WzUserInfo>().eq("user_code",userCode).eq("type",EnWzUser.USERINFO_TYPE_MERCHANT.getIndex()).eq("is_default",EnWzUser.USERINFO_isDefault_true.getIndex()));
            for(WzUserInfo u:userInfos){
                u.setIsDefault(EnWzUser.USERINFO_isDefault_false.getIndex());
                userInfoMapper.updateById(u);
            }
        }
        userInfo.setMerchantFulladdress(merchantFullAddress);
        userInfo.setMerchantArea(merchantArea);
        if(!StringUtils.isBlankStr(merchantAddress)){
            userInfo.setMerchantAddress(merchantAddress);
        }
        userInfo.setAdCode(adCode);
        userInfo.setMerchantTel(merchantTel);
        userInfo.setMerchantName(merchantName);
        userInfo.setMerchantLatitude(merchantLatitude);
        userInfo.setMerchantLongitude(merchantLongitude);
        userInfo.setUserCode(userCode);
        userInfo.setIsDefault(isDefault);
        userInfo.setType(EnWzUser.USERINFO_TYPE_MERCHANT.getIndex());
        if(StringUtils.isBlankStr(userInfoId)){
            userInfoMapper.insert(userInfo);
        }else{
            userInfoMapper.updateById(userInfo);
            List<WzAdvMap> advMaps = advMapMapper.selectList(new EntityWrapper<WzAdvMap>().eq("user_info_id",userInfoId));
            for(WzAdvMap advMap : advMaps){
                advMap.setLongitude(userInfo.getMerchantLongitude());
                advMap.setLatitude(userInfo.getMerchantLatitude());
                advMap.setMerchantFullAddress(userInfo.getMerchantFulladdress());
                advMap.setMerchantTel(userInfo.getMerchantTel());
                advMapMapper.updateById(advMap);
            }
        }
        return Res.success();
    }

    /**
     * 地址设为默认
     */
    @Transactional
    @PostMapping("userInfoIsDefault")
    public Res userInfoIsDefaults(@RequestBody ParamMap paramMap){
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        int isDefault = paramMap.getIntMisValid("isDefault");
        String userInfoId = paramMap.getStrMisValid("userInfoId");
        //修改默认
        if(isDefault == EnWzUser.USERINFO_isDefault_true.getIndex()){
            List<WzUserInfo> userInfos = userInfoMapper.selectList(new EntityWrapper<WzUserInfo>().eq("user_code",userCode).eq("type",EnWzUser.USERINFO_TYPE_MERCHANT.getIndex()).eq("is_default",EnWzUser.USERINFO_isDefault_true.getIndex()));
            for(WzUserInfo u:userInfos){
                u.setIsDefault(EnWzUser.USERINFO_isDefault_false.getIndex());
                userInfoMapper.updateById(u);
            }
        }
        WzUserInfo userInfo = userInfoMapper.selectById(userInfoId);
        userInfo.setIsDefault(isDefault);
        userInfoMapper.updateById(userInfo);
        return Res.success();
    }

    /**
     * 地址删除
     */
    @PostMapping("userInfoDelete")
    public Res userInfoDeletes(@RequestBody ParamMap paramMap){
        Long userInfoId = paramMap.getLongMisValid("userInfoId");
        List<WzAdv> advs = advMapper.selectList(new EntityWrapper<WzAdv>().eq("user_info_id",userInfoId).ge("status",EnWzAdv.STATUS_WaitCheck.getIndex()));
        List<WzAdvMap> advMaps = advMapMapper.selectList(new EntityWrapper<WzAdvMap>().eq("user_info_id",userInfoId));
        if(advs.size() > 0 || advMaps.size() > 0){
            return Res.fail("此地址正在被使用，不可删除!");
        }
        int r = userCouponMapper.selectCount(new EntityWrapper<WzUserCoupon>().eq("user_info_id",userInfoId.toString()).eq("status", EnWzCoupon.STATUS_Normal.getIndex()));
        if(r > 0){
            return Res.fail("此地址正在被使用，不可删除!");
        }
        WzUserInfo userInfo = userInfoMapper.selectById(userInfoId);
        userInfoMapper.deleteById(userInfo);
        return Res.success();
    }

    /**
     * 广告发布记录详情
     */
    @PostMapping("advReleaseRecordsDetail")
    public Res advReleaseRecordsDetails(@RequestBody ParamMap paramMap){
        Long advId = paramMap.getLongMisValid("advId");
        List<Map<String,Object>> advs = advMapper.selectMaps(new EntityWrapper<WzAdv>().eq("adv_id",advId));
        int recipientsNumber = Integer.parseInt(advs.get(0).get("pushNumber").toString());
        int totalReward = Integer.parseInt(advs.get(0).get("totalReward").toString());
        int surplusReward = Integer.parseInt(advs.get(0).get("surplusReward").toString());
        int rewardPay = totalReward - surplusReward;//已支出金额
        advs.get(0).put("recipientsNumber",recipientsNumber);//支出总数
        advs.get(0).put("rewardPay",rewardPay);//支出金额
        advs.get(0).put("couponUsedNumber",0);//优惠券使用数量
        advs.get(0).put("couponReceiveNumber",0);//优惠券领取数量
        Date end = DateUtil.toDate(advs.get(0).get("endTime").toString());
        Date yestoday = DateUtil.yesterday(end,1);
        advs.get(0).put("endTime",DateUtil.toStringDataTime(yestoday));
        //发红包服务费
        advs.get(0).put("redPacketFee", Consts.redPacketFee);
        //分享数据
        if(Integer.parseInt(advs.get(0).get("shareReward").toString()) != 0){
            List<Map<String, Object>> totalshareNumber = advShareMapper.selectMaps(Condition.create().setSqlSelect("sum(share_number) As totalshareNumber").eq("adv_id",advId));
            List<Map<String, Object>> totalclickNumber = advShareMapper.selectMaps(Condition.create().setSqlSelect("sum(click_number) As totalclickNumber").eq("adv_id",advId));
            List<WzAdvShare> advShares = advShareMapper.selectList(new EntityWrapper<WzAdvShare>().eq("adv_id",advId).ne("share_reward",0));
            if(totalshareNumber.get(0) == null){
                advs.get(0).put("totalshareNumber", "0");//总分享数
            }else{
                advs.get(0).put("totalshareNumber", totalshareNumber.get(0).get("totalshareNumber").toString());//总分享数
            }
            if(totalclickNumber.get(0) == null){
                advs.get(0).put("totalclickNumber", "0");//总分享数
            }else{
                advs.get(0).put("totalclickNumber", totalclickNumber.get(0).get("totalclickNumber").toString());//总点击数
            }
            advs.get(0).put("shareNumber", advShares.size());//参与分享人数
            String token = HttpKit.getRequest().getHeader(jwtProperties.getHeader()).substring(7);
            advs.get(0).put("rewardShareLink", "http://50wz.viphk1.ngrok.org/wz/wzShare/share?advId="+advId+"&type=1&userCode="+token+"");
            int count = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("adv_id",advId).eq("user_code",Long.parseLong(advs.get(0).get("userCode").toString())));
            if(count > 0){
                advs.get(0).put("isShare", 1);
            }else{
                advs.get(0).put("isShare", 0);
            }
        }else{
            advs.get(0).put("totalshareNumber", "");//总分享数
            advs.get(0).put("totalclickNumber", "");//总点击数
            advs.get(0).put("shareNumber", "");//参与分享人数
            advs.get(0).put("rewardShareLink", "");
            advs.get(0).put("isShare", 0);
        }
        if(advs.get(0).get("shareAverageReward").toString().equals("0")){
            advs.get(0).put("shareUserNumber", 0);//可参与分享总人数
        }else{
            advs.get(0).put("shareUserNumber", Integer.parseInt(advs.get(0).get("shareReward").toString())/Integer.parseInt(advs.get(0).get("shareAverageReward").toString()));//可参与分享总人数
        }
        advs.get(0).put("partitionNumber", 0);//参与瓜分人数
        //去除不需要参数
        advs.get(0).remove("rewardFee");
        advs.get(0).remove("rewardAverage");
        return Res.success(advs.get(0));
    }

    /**
     * 广告支出记录
     */
    @PostMapping("adv.releaseRecords.rewardRecords")
    public Res advReleaseRecordsRewardRecords(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long advId = paramMap.getLongMisValid("advId");
        List<Map<String,Object>> userAdvRecords = new ArrayList<>();
        List<Map<String,Object>> adv = cacheService.adv(advId);
        if(adv.get(0).get("subtype").toString().equals("1") || adv.get(0).get("subtype").toString().equals("7")){
            userAdvRecords = userAdvRecordMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzUserAdvRecord>().eq("type",EnWzAdv.ADV_RECORD_REWARD.getIndex()).eq("adv_id",advId).orderBy("create_time",false));
        }else if(adv.get(0).get("subtype").toString().equals("50") || adv.get(0).get("subtype").toString().equals("53")){
            userAdvRecords = userAdvRecordMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzUserAdvRecord>().eq("adv_id",advId).orderBy("reward",false).orderBy("create_time",false));
        }
        paramMap.put("list",userAdvRecords);
        return Res.success(paramMap);
    }

}
